package com.atguigu.study;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareDateDemo{
    private int flog=1;
    final Lock lock=new ReentrantLock();
    final Condition condition1=lock.newCondition();
    final Condition condition2=lock.newCondition();
    final Condition condition3=lock.newCondition();
    public void print5() throws InterruptedException {
        lock.lock();
        try {
            while (flog!=1){
                condition1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            flog=2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }
    public void print10() throws InterruptedException {
        lock.lock();
        try {
            while (flog!=2){
                condition2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            flog=3;
            condition3.signal();
        } finally {
        lock.unlock();
        }
    }
    public void print15()throws InterruptedException{
        lock.lock();
        try {
            while (flog!=2){
                condition3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            flog=1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadOrderAccessDemo {
    public static void main(String[] args) {
        ShareDateDemo shareDateDemo = new ShareDateDemo();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDateDemo.print5();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"A").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDateDemo.print5();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"B").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareDateDemo.print5();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"C").start();
    }
}
